package com.example.demo.controller;



import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")

public class UserController {
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public boolean User(String userName, String password, HttpServletRequest request) {
        //第一种,userName.equals("")（如果username为空指针，会报空指针异常）一般不这么写，而是把常量写在前面
        if (userName == null || ("").equals(userName)) {
            return false;
        }
        //Spring提供的一种方式
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength((password))) {
            return false;
        }
        //不为空校验账号密码是否正确
        if (("ameki").equals(userName) && ("ameki").equals(password)) {
            //设置session对象,如果有session对象就返回，没有就创建,可使用HttpSession session
            //也可以使用如下
            HttpSession session = request.getSession();
            session.setAttribute("userName", userName);
            session.setAttribute("password", password);
            return true;
        }

        return false;
    }

    @RequestMapping(value = "/getLoginUser")

    // public String getLoginUser(HttpSession session){
    //return (String)session.getAttribute("userName")
      //}
    public String getLoginUser(HttpServletRequest request){
        //session读取
        HttpSession session = request.getSession(true);
        String username=(String)session.getAttribute("userName");
        if(session.getAttribute("userName")!=null){
            return username;
        }
        return "";
    }
}
